package com.hyq.market.api;

import android.net.Uri;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.hyq.market.base.AbsModel;
import com.hyq.market.utils.HttpConnetionUtil;

import org.greenrobot.eventbus.EventBus;
import org.xutils.common.util.KeyValue;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.http.body.RequestBody;
import org.xutils.x;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by hl on 2017/6/9.
 */

public abstract class AbsServiceUtils extends AbsModel implements org.xutils.common.Callback.CommonCallback<String> {

    public Gson gson = new Gson();
    public int sendCode;

    public void sendToServer(RequestParams params) {
        sendToServer(params, 0);
    }

    public void sendToServer(RequestParams params, int post) {
        sendToServer(params, post, false);
    }

    public void sendToServer(RequestParams params, int post, boolean isloading) {
//        if (NetUtils.isNetworkAvailable(MyApp.getInstance().getApplicationContext()) ){
//        }
        System.out.println("请求地址：" + params.getUri());
        for (KeyValue keyValue : params.getQueryStringParams()) {
            System.out.println("请求参数" + keyValue.key + ":" + keyValue.getValueStr());
        }
        for (KeyValue keyValue : params.getBodyParams()) {
            System.out.println("请求参数" + keyValue.key + ":" + keyValue.getValueStr());
        }
        params.setConnectTimeout(5000);
        if (post == 1) {
            if (params.getQueryStringParams().size()>0){
                Map<String,String> map=new HashMap<>();
                for (KeyValue keyValue : params.getQueryStringParams()) {
                    System.out.println("请求参数" + keyValue.key + ":" + keyValue.getValueStr());
                }
                try {
                    params.setRequestBody(new UrlEncodedParamsBody(map,"utf-8"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            x.http().post(params,this);
            return;
        }
        x.http().get(params, this);

    }

    @Override
    public void onSuccess(String result) {
        System.out.println("返回结果:" + result);
        if (netCallback == null) {
            sendMsgToView(fromJson(result));
        } else {
            netCallback.netSucceed(fromJson(result), sendCode);
        }
    }

    @Override
    public void onError(Throwable ex, boolean isOnCallback) {
        if (netCallback != null)
            netCallback.netFailed(ex, 400);
    }

    @Override
    public void onCancelled(CancelledException cex) {
        if (netCallback != null)
            netCallback.netFailed(cex, 300);
    }

    @Override
    public void onFinished() {

    }


    public <E> void sendMsgToView(E e) {
        EventBus.getDefault().post(e);
    }


    public <E> void sendMsgToView(String json, Class<E> e) {
        E evnet = gson.fromJson(json, e);
        if (evnet != null)
            sendMsgToView(evnet);
    }

    public abstract <T> T fromJson(String json);




    public class UrlEncodedParamsBody implements RequestBody {
        private byte[] content;
        private String charset = "UTF-8";
        public UrlEncodedParamsBody(Map<String,String> map, String charset) throws IOException {
            if (!TextUtils.isEmpty(charset)) {
                this.charset = charset;
            }
            StringBuilder contentSb = new StringBuilder();
            if(null!=map){
                for(Map.Entry<String, String> entry : map.entrySet()) {
                    String name = entry.getKey();
                    String value = entry.getValue();
                    if (!TextUtils.isEmpty(name) && value != null) {
                        if (contentSb.length() > 0) {
                            contentSb.append("&");
                        }
                        contentSb.append(Uri.encode(name, this.charset))
                                .append("=")
                                .append(Uri.encode(value, this.charset));
                    }
                }
            }

            this.content = contentSb.toString().getBytes(this.charset);
        }

        @Override
        public long getContentLength() {
            return content.length;
        }

        @Override
        public void setContentType(String contentType) {
        }

        @Override
        public String getContentType() {
            return "application/x-www-form-urlencoded;charset=" + charset;
        }

        @Override
        public void writeTo(OutputStream sink) throws IOException {
            sink.write(this.content);
            sink.flush();
        }
    }



}
